<?php
/**
 * @ClassName: Operationdata
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-11-07 17:35
 * @Version: V1.0.0
 */

namespace app\admin\controller\agent;

use app\common\enum\CommonEnum;
use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Operationdata extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected $statistical_data = '';

    protected function initialize()
    {
        $this->dataModel = new model\OperationCenter();

        $this->pageTitle = '运营中心数据';
        $this->sortOrder = 'id desc';
        $this->pagesize = 10;
        $this->pk = 'id';
        $this->selectTextField = '{id}#{name}';
        $this->selectSearch = 'id|name';

        $this->indexWith = ['member'];
    }

    protected function buildDataList()
    {
        $page = input('post.__page__/d', 1);
        $page = $page < 1 ? 1 : $page;

        $where = $this->filterWhere();
        $table = $this->table;

        $pagesize = input('post.__pagesize__/d', 0);

        $this->pagesize = $pagesize ?: $this->pagesize;

        $total = $this->dataModel::where($where)->count();
        $data = $this->dataModel::where($where)
            ->with(['member'])
            ->order('create_time desc')
            ->limit(($page - 1) * $this->pagesize, $this->pagesize)
            ->select()->toArray();

        // 移除 status 条件
        /*$new_where = [];
        foreach ($where as &$item) {
            if ($item[0] != 'pay_status') {
                $new_where[] = $item;
            }
        }*/

        $total_amount = 0;
        $withdrawn = 0;
        $unwithdrawn = 0;
        $open_withdrawn = 0;
        $open_unwithdrawn = 0;
        $this->statistical_data = "总收入：{$total_amount}，已提现：{$withdrawn}，未提现：{$unwithdrawn}，开户奖已提现：{$open_withdrawn}，开户奖未提现：{$open_unwithdrawn}";

        $this->buildTable($data);
        $table->fill($data);
        $table->paginator($total, $this->pagesize);

        return $data;
    }

    /**
     * 构建搜索
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;
        $search->select('member_id', '会员')->dataUrl(url('/admin/member/selectPage'));
        $search->select('parent_id', '上级运营中心')->dataUrl(url('/admin/agent.operation/selectPage'));
        $search->select('center_type', '运营中心类型')->options(model\OperationCenter::$center_types);
        $search->select('opening_type', '开通方式')->options(model\OperationCenter::$opening_types);
        $search->text('name', '运营中心名称');
        $search->text('contact_name', '运营中心联系人');
        $search->text('mobile', '运营中心联系电话');
        $search->select('province', '省份')->dataUrl(url('api/areacity/province'), 'ext_name')->withNext(
            $search->select('city', '城市')->dataUrl(url('api/areacity/city'), 'ext_name')->withNext(
                $search->select('area', '地区')->dataUrl(url('api/areacity/area'), 'ext_name')
            )
        );
        $search->text('address', '运营中心地址');
        $search->select('status', '运营中心状态')->options(CommonEnum::examineText(true));

        $search->datetime('start', '时间')->placeholder('起始');
        $search->datetime('end', '~')->placeholder('截止');
    }

    /**
     * 构建查询条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->isGet() ? request()->param() : request()->post();

        $where = [];
        if (!empty($searchData['member_id'])) {
            $where[] = ['member_id', 'eq', $searchData['member_id']];
        }
        if (!empty($searchData['parent_id'])) {
            $where[] = ['parent_id', 'eq', $searchData['parent_id']];
        }
        if (!empty($searchData['center_type'])) {
            $where[] = ['center_type', 'eq', $searchData['center_type']];
        }
        if (!empty($searchData['opening_type'])) {
            $where[] = ['opening_type', 'eq', $searchData['opening_type']];
        }
        if (!empty($searchData['name'])) {
            $where[] = ['name', 'eq', '%' . $searchData['name'] . '%'];
        }
        if (!empty($searchData['contact_name'])) {
            $where[] = ['contact_name', 'eq', '%' . $searchData['contact_name'] . '%'];
        }
        if (!empty($searchData['mobile'])) {
            $where[] = ['mobile', 'eq', '%' . $searchData['mobile'] . '%'];
        }
        if (!empty($searchData['province'])) {
            $where[] = ['province', 'eq', $searchData['province']];
        }
        if (!empty($searchData['city'])) {
            $where[] = ['city', 'eq', $searchData['city']];
        }
        if (!empty($searchData['area'])) {
            $where[] = ['area', 'eq', $searchData['area']];
        }
        if (!empty($searchData['address'])) {
            $where[] = ['address', 'eq', '%' . $searchData['address'] . '%'];
        }
        if (!empty($searchData['status'])) {
            $where[] = ['status', 'eq', $searchData['status']];
        }
        if (!empty($searchData['start'])) {
            $where[] = ['create_time', 'egt', $searchData['start']];
        }
        if (!empty($searchData['end'])) {
            $where[] = ['create_time', 'elt', $searchData['end']];
        }

        return $where;
    }

    /**
     * 构建表格
     * @param $data
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $table->show('id', 'ID');
        $table->show('member_id', "会员")->to('{member_id}#{member.nickname}');
        $table->show('parent_name', '上级运营中心')->default('--');
        $table->image('avatar', '头像')->thumbSize(50, 50)->default('/static/images/touxiang.png');
        $table->match('center_type', '运营中心类型')->options(model\OperationCenter::$center_types);
        $table->match('opening_type', '开通方式')->options(model\OperationCenter::$opening_types)
            ->mapClassGroup([[1, 'success'], [2, 'default']]);
        $table->show('name', '运营中心名称');
        $table->show('pcat', '运营区域');
        $table->show('contact_name', '运营中心联系人');
        $table->show('mobile', '运营中心联系电话');
        /*$table->select('province', '省份')->dataUrl(url('api/areacity/province'), 'ext_name')->withNext(
            $table->select('city', '城市')->dataUrl(url('api/areacity/city'), 'ext_name')->withNext(
                $table->select('area', '地区')->dataUrl(url('api/areacity/area'), 'ext_name')
            )
        );*/
        $table->show('address', '运营中心地址');
        $table->show('total_amount', '总收入');
        $table->show('balance', '余额');
        $table->match('status', '运营中心状态')->options(CommonEnum::examineText(true))
            ->mapClassGroup([[0, 'default'], [1, 'success'], [2, 'danger']]);
        $table->show('verify_time', '审核时间')->default('--');

        $table->fields('create_times', '申请/更新时间')->with(
            $table->show('create_time', '申请时间'),
            $table->show('update_time', '更新时间')
        )->getWrapper()->addStyle('width:160px');

        foreach ($data as &$d) {
            $d['__h_p__'] = $d['status'] != 0;
            $d['__h_unp__'] = $d['status'] != 0;
        }
        unset($d);

        $table->sortable('id, create_time');

        $table->addTop()->display($this->statistical_data)->addStyle("font-size:16px; font-weight: bold; color: #000;");

        $table->getToolbar()
            ->btnAdd()
            ->btnEnableAndDisable('通过', '拒绝')
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnPostRowid('pass', url('/admin/agent.operation/enable', ['state' => 1]), '通过', 'btn-success', '', '')
            ->btnPostRowid('unpass', url('/admin/agent.operation/enable', ['state' => 0]), '拒绝', 'btn-danger', '', '')
            ->mapClass([
                'pass' => ['hidden' => '__h_p__'],
                'unpass' => ['hidden' => '__h_unp__'],
            ]);
    }

    /**
     * 构建表单
     * @param $isEdit
     * @param $data
     * @return void
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;
        $form->select('parent_id', '上级运营中心')->dataUrl(url('/admin/agent.operation/selectPage'));
        $form->select('member_id', '会员')->dataUrl(url('/admin/member/selectPage'))->required();
        $form->image('avatar', '头像')->thumbSize(50, 50);
        $form->select('opening_type', '开通方式')->options(model\OperationCenter::$opening_types)->required();
        $form->text('name', '运营中心名称')->required();
        $form->text('contact_name', '运营中心联系人')->required();
        $form->text('mobile', '运营中心联系电话')->required();
        $form->select('center_type', '运营中心类型')->options(model\OperationCenter::$center_types)->required()->when(3)->with(
            $form->select('province', '省份')->dataUrl(url('api/areacity/province'), 'ext_name')->required()
        )->when(2)->with(
            $form->select('province', '省份')->dataUrl(url('api/areacity/province'), 'ext_name')->required()->withNext(
                $form->select('city', '城市')->dataUrl(url('api/areacity/city'), 'ext_name')->required()
            )
        )->when(1)->with(
            $form->select('province', '省份')->dataUrl(url('api/areacity/province'), 'ext_name')->required()->withNext(
                $form->select('city', '城市')->dataUrl(url('api/areacity/city'), 'ext_name')->required()->withNext(
                    $form->select('area', '地区')->dataUrl(url('api/areacity/area'), 'ext_name')->required()
                )
            )
        );
        $form->text('address', '运营中心地址')->required();
        $form->radio('status', '运营中心状态')->options(CommonEnum::examineText(true))->default(1)->required()->when(2)->with(
            $form->textarea('remark', '备注')
        );
    }

    /**
     * 保存
     * @param $id
     * @return \think\response\Json|\tpext\think\View
     */
    private function save($id = 0)
    {
        $data = request()->post();
        $result = $this->validate($data, []);

        if (!$result) {
            $this->error($result);
        }

        if ($data['parent_id'] && $data['parent_id'] == $id) {
            return json(['code' => 0, 'msg' => '上级运营中心不能是自己']);
        }

        if (($data['center_type'] == 2 || $data['center_type'] == 1) && !$data['parent_id']) {
            return json(['code' => 0, 'msg' => '开通市级和区县运营中心请先选择上级运营中心']);
        }

        if ($id) {
            // 编辑
            $center = model\OperationCenter::get($id);
            // 运营中心之前没有审核，本次编辑审核通过
            if (!$center['verify_time'] && $data['status'] == 1) {
                $data['verify_time'] = date_now();
            }

            // 检测当前区域是否已经开通运营中心
            $check = true;
            if ($data['center_type'] == 3) {
                $check = model\OperationCenter::where(['center_type' => 3, 'province' => $data['province']])->where('id', '<>', $id)->find();
            } elseif ($data['center_type'] == 2) {
                $check = model\OperationCenter::where(['center_type' => 2, 'city' => $data['city']])->where('id', '<>', $id)->find();
            } elseif ($data['center_type'] == 1) {
                $check = model\OperationCenter::where(['center_type' => 1, 'area' => $data['area']])->where('id', '<>', $id)->find();
            }
            if ($check) {
                return json(['code' => 0, 'msg' => '当前区域已经开通运营中心，请勿重复开通']);
            }

            $res = $this->dataModel->allowField(true)->isUpdate(true, [$this->getPk() => $id])->save($data);
        } else {
            // 新增
            if ($data['status'] == 1) {
                $data['verify_time'] = date_now();
            }

            // 检测当前区域是否已经开通运营中心
            $check = true;
            if ($data['center_type'] == 3) {
                $check = model\OperationCenter::where(['center_type' => 3, 'province' => $data['province']])->find();
            } elseif ($data['center_type'] == 2) {
                $check = model\OperationCenter::where(['center_type' => 2, 'city' => $data['city']])->find();
            } elseif ($data['center_type'] == 1) {
                $check = model\OperationCenter::where(['center_type' => 1, 'area' => $data['area']])->find();
            }
            if ($check) {
                return json(['code' => 0, 'msg' => '当前区域已经开通运营中心，请勿重复开通']);
            }

            $res = $this->dataModel->allowField(true)->isUpdate(false)->save($data);
        }

        if ($res) {
            // 更新会员运营中心信息
            if ($data['status'] == 1) {
                $this->upMember($data);
            }

            return $this->builder()->layer()->closeRefresh(1, __blang('bilder_save_succeeded'));
        } else {
            return $this->builder()->layer()->closeRefresh(0, __blang('bilder_save_failed'));
        }
    }

    /**
     * 审核
     * @param $state
     * @return \think\response\Json
     */
    public function enable($state)
    {
        $ids = input('post.ids', '');
        $ids = array_filter(explode(',', $ids), 'strlen');

        if (empty($ids)) {
            return json(['code' => 0, 'msg' => '参数有误']);
        }

        if ($state) {
            $remark = '审核通过';
            $status = 1;
        } else {
            $remark = '审核不通过';
            $status = 2;
        }
        $res = 0;
        foreach ($ids as $id) {
            if ($this->trans($id, $remark, $status)) {
                $res += 1;
            }
        }
        if ($res) {
            return json(['code' => 1, 'msg' => '成功操作' . $res . '条数据']);
        } else {
            trace('审核操作失败');
            return json(['code' => 0, 'msg' => '审核操作失败']);
        }
    }

    /**
     * 审核操作
     * @param $id
     * @param $remark
     * @param $state
     * @return model\OperationCenter|\think\response\Json
     */
    private function trans($id, $remark, $state = 1)
    {
        $records = model\OperationCenter::where('id', $id)->find();

        if (!$records) {
            return json(['code' => 0, 'msg' => '记录不存在']);
        }
        if ($records['status'] != 0) {
            return json(['code' => 0, 'msg' => '记录状态不是待审核状态']);
        }

        $up_data = [
            'status' => $state,
            'remark' => $remark,
            'update_time' => date_now(),
        ];
        if ($state == 1) {
            $up_data['verify_time'] = date_now();
        }
        $res = true;
        $res = model\OperationCenter::where('id', $id)->update($up_data);

        return $res;
    }

    /**
     * 更新会员运营中心信息
     * @param $data
     * @return bool
     */
    private function upMember($data)
    {
        $member = model\Member::where('id', $data['member_id'])->find();
        if (!$member) {
            return false;
        }

        $up_data = [
            'operation_level' => $data['center_type'],
            'operation_province' => $data['province'],
            'operation_city' => isset($data['city']) ?? 0,
            'operation_area' => isset($data['area']) ?? 0,
            'update_time' => date_now(),
        ];

        $res = model\Member::where('id', $data['member_id'])->update($up_data);

        if (!$res) {
            return false;
        }
        return true;
    }

}